<script setup>
import { ElPagination } from 'element-plus';
import index, {useStore} from "vuex";
import { computed, ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from "axios";


let dialogFormVisible = ref(false);
let pmArr = ref([])
const user = computed(() => store.state.user)

let changeId = ref(0);


const store = useStore()
// 来显示搜索框和原数据框的显示和隐藏
let isShow = ref(true);

//搜索关键字
let searchAll = ref("");

let replyContent = ref("");


// -----------------------------------------

const currentPage = ref(1); // 当前页码 默认是1
const pageSize = ref(5); // 每页显示的条目数  默认是5
const totalItems = computed(()=> pmArr.value.length); // 总条目数，userArr已经初始化
// 当前页的条目数据
const itemsArr = computed(()=> pmArr.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
))
// -----------------------------------------

const handleSizeChange = (s) => {
  pageSize.value = s;
};
const handleCurrentChange = (newPage) => {
  console.log("所要显示的页面:"+newPage);
  currentPage.value = newPage;
};

// -----------------------------------------
const handleDelete = (id) => {
  axios.delete('consultationEvaluation/' + id)
      .then(response => {
        ElMessage.success('删除成功');
        initializeData();
      })
      .catch(error => {
        console.error(error);
        ElMessage.error('删除失败');
      });

}
const resetSerchbtn = () => {
  isShow.value = true;
  searchAll.value = "";
}
const serchBtn = () => {
  isShow.value = false;
}

const filterPMArr = computed(() =>
    //filter接受一个回调函数作为参数，并返回一个新数组，该数组包含所有使得回调函数返回true的元素
    pmArr.value.filter(
        (data) =>
            !searchAll.value ||
            String(data.users.userId).includes(String(searchAll.value)) ||
            String(data.consultationEvaluation.evaluationRating).includes(String(searchAll.value))||
            data.users.userNickname.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.consultationEvaluation.evaluationContent.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.consultationEvaluation.evaluationTime.toLowerCase().includes(searchAll.value.toLowerCase())
    )
)
// 封装获取数据的方法
const fetchData = async (consultantId) => {
  try {
    const res = await axios.get('consultationAppointment/selectByConsultantId?consultantId='+consultantId);
    if (res.data.code === 200) {
      console.log('获取到的数据:', res.data.data)
      return res.data.data;
    } else {
      throw new Error('加载失败');
    }
  } catch (error) {
    ElMessage.error(error.message);
    throw error;
  }
};

// 封装处理时间格式的方法
const formatQuestionTime = (items) => {
  return items.map(item => {
    // 检查 consultationEvaluation 是否存在，避免潜在的 undefined 错误
    const evaluationTime = item.consultationEvaluation
        ? new Date(item.consultationEvaluation.evaluationTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false // 使用24小时制
        })
        : null;

    // 返回一个新的对象，包含所有原始属性和格式化后的 evaluationTime
    return {
      ...item,
      consultationEvaluation: {
        ...item.consultationEvaluation,
        evaluationTime: evaluationTime
      }
    };
  });
};

// 封装初始化数据的方法
const initializeData = async () => {
  const consultantId = user.value.consultantId;
  try {
    const data = await fetchData(consultantId);
    pmArr.value = formatQuestionTime(data);
    console.log(pmArr.value);
  } catch (error) {
    // 错误已经在 fetchData 中处理过了
  }
};

const renderStarImages = (rating) => {
  const stars = [];
  for (let i = 0; i < 5; i++) {
    const imgSrc = i < rating ? require('@/assets/@2x_star_y.png') : require('@/assets/@2x_star_b.png');
    stars.push(`<img src="${imgSrc}" alt="star" style="width: 20px; height: 20px;" />`);
  }
  return stars.join('');
}

// 在组件挂载时调用初始化方法
onMounted(initializeData);


</script>

<template>
  <ul class="xitongYonghu" style="z-index: 1">

    <li class="xitongYonghu-top">

      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">



        <li style="width: 420px">
          <input style="height: 32.5px;width: 250px;box-sizing: border-box;padding: 5px 10px;border-radius: 5px;border: none" type="text" v-model="searchAll">
          <el-button @click="serchBtn" style="margin-left: 10px">
            🔍搜索
          </el-button>
          <el-button @click="resetSerchbtn">
            重置
          </el-button>
        </li>

      </ul>
    </li>
    <li>
      <el-table v-if="isShow" :data="itemsArr" style="width: 99%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="users.userId" label="UserId" width="100px" />
        <el-table-column prop="users.userNickname" label="用户昵称" width="150px" />
        <el-table-column label="星级" width="150px">
          <template #default="scope">
            <div v-html="renderStarImages(scope.row.consultationEvaluation.evaluationRating)"></div>
          </template>
        </el-table-column>
        <el-table-column prop="consultationEvaluation.evaluationContent" label="评价内容" width="500px" />
        <el-table-column prop="consultationEvaluation.evaluationTime" label="评价时间" width="200px" />
        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.consultationEvaluation.evaluationId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table v-else :data="filterPMArr" style="width: 99%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="users.userId" label="UserId" width="100px" />
        <el-table-column prop="users.userNickname" label="用户昵称" width="150px" />
        <el-table-column label="星级" width="150px">
          <template #default="scope">
            <div v-html="renderStarImages(scope.row.consultationEvaluation.evaluationRating)"></div>
          </template>
        </el-table-column>
        <el-table-column prop="consultationEvaluation.evaluationContent" label="评价内容" width="500px" />
        <el-table-column prop="consultationEvaluation.evaluationTime" label="评价时间" width="200px" />
        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.consultationEvaluation.evaluationId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </li>
    <li>
      <el-pagination v-if="isShow"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[3, 5, 10]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalItems">
      </el-pagination>
      <p v-else></p>
    </li>
  </ul>



</template>

<style scoped>
.xitongYonghu{
  width: 99%;
  background-color: #cccccc;
  padding: 15px;
}
.xitongYonghu li{
  width: 100%;
  border-radius: 5px;
}
.xitongYonghu-top {
  background-color: transparent;
  margin-bottom: 10px;
}
.el-pagination{
  margin-top: 10px;
}
</style>